#include <cstdio>
#include <algorithm>

using namespace std;
/*
 * in this problem, it is possible that no mst generated! Cause the number of node and the number of line have no relationship.
 * so we need to judge whether every node is in one tree.
 */
#define M 101

int tree[M];

int find_root(int x);

class graph_edge {
public:
    int a, b;
    int cost;

    bool operator<(const graph_edge &e) const {
        return cost < e.cost;
    }
} edge[6000];

int main(int argc, char const *argv[]) {
    int n, m;
    while (scanf("%d", &n) != EOF && n != 0) {
        scanf("%d", &m);
        for (int i = 0; i < n; ++i)
            scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].cost);
        sort(edge, edge + n);
        for (int i = 1; i <= m; ++i)
            tree[i] = -1;

        int result = 0;
        for (int i = 0; i < n; ++i) {
            int a_inedx = find_root(edge[i].a);
            int b_index = find_root(edge[i].b);
            if (a_inedx != b_index) {
                tree[a_inedx] = b_index;
                result += edge[i].cost;
            }
        }
        int union_num = 0;
        for (int i = 1; i <= m; i++){
            if (tree[i] == -1)
                union_num++;
        }
        if (union_num > 1)
            printf("?\n");
        else
            printf("%d\n", result);
    }
    return 0;
}

int find_root(int x) {
    if (tree[x] == -1)
        return x;
    else {
        int temp_index = find_root(tree[x]);
        tree[x] = temp_index;
        return temp_index;
    }
}